/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/***************************************************************************
 * Name: xdialer_impl.cpp
 *
 * Purpose: xdialer base implmentation define and implementation
 *
 * Developer:
 *   wen.gu , 2023-10-30
 *
 * TODO:
 *
 ***************************************************************************/

#include "xbus/com/internal/xdialer_impl.h"

#include <atomic>

#include "xbus/com/xutils.h"
#include "xbus/com/internal/udp_session.h"
#include "xbus/com/internal/sock_session.h"
#include "xbus/core/xtime.h"

namespace xbus::com::internal {

using namespace xbus::core;
using ConnectionId = XDialerImpl::ConnectionId;

static XResult<XDialerSp> TrySockConnect(const std::string& url, int32_t port, const std::string& session_name) {
    XSocketType sock_type = ComType2SockType(ParseComType(url));
    if (sock_type != XSocketType::None) {
        
        auto res = XSocketOpen(sock_type, false, url, port);
        if (!res) {
            return XResult<XDialerSp>::FromError(res.error());
        }
        XSessionSp session = nullptr;
        if (sock_type == XSocketType::UDP) {
            session = std::make_shared<UdpSession>(res.value(), session_name);
        } else {
            session = std::make_shared<SockSession>(res.value(), session_name);
        }

        if (!session) {
            XSocketClose(res.value());
            return XResult<XDialerSp>::FromError(XErrC::InsufficientReousces);
        }

        return std::make_shared<XDialer>(session);
    } 

    return XResult<XDialerSp>::FromError(XErrC::Unsupported);
}

XDialerImpl::~XDialerImpl() {
    for (auto it: connection_map_) {
        ConnectionInfo& cinfo = it.second;
        if (cinfo.timer_worker) {
            cinfo.running = false;
            cinfo.timer_worker->join();
            cinfo.timer_worker = nullptr;          
        }
    }
    connection_map_.clear();
}

XDialerImpl::XDialerImpl() {

}


//static 
XDialerImpl& XDialerImpl::getInstance() {
    static XDialerImpl impl;
    return impl;
}


XResult<XDialerSp> XDialerImpl::tryConnect(const std::string& url, int32_t port /*= 0*/, int32_t timeout_ms /*= core::WaitType::NoWait*/) {
    if (url.empty()) {
        return XResult<XDialerSp>::FromError(XErrC::InvalidArgument);
    }
    static_cast<void>(timeout_ms);
    return TrySockConnect(url, port, url);
}

XResult<ConnectionId> XDialerImpl::registerConnection(const std::string& url, int32_t port, OnConnectionHandler handler) {
    if (url.empty() || !handler) {
        return XResult<ConnectionId>::FromError(XErrC::InvalidArgument);
    }
    static std::atomic<ConnectionId> next_connection_id;
    ConnectionId connection_id = next_connection_id.fetch_add(1);
    std::unique_lock<std::mutex> al(lock_);
    connection_map_[connection_id] = ConnectionInfo();
    auto it = connection_map_.find(connection_id);

    if (it != connection_map_.end()) {
        ConnectionInfo& cinfo = it->second;
        cinfo.url = url;
        cinfo.port = port;
        cinfo.running = true;
        cinfo.timer_worker = std::make_shared<XThread>("cw:" + url, [&cinfo, handler]() {
            while (cinfo.running) {
                auto res = TrySockConnect(cinfo.url, cinfo.port, cinfo.url);
                if (res) {
                    handler(res.value());
                    break; //todo, the work flow is right?
                }
                core::SleepMs(XBUS_DIALER_CONNECTION_TRY_INTERVAL_MS);
            }
        });

        if (cinfo.timer_worker->start()) {
            return connection_id;
        }
        connection_map_.erase(it); 
    }

    return XResult<ConnectionId>::FromError(XErrC::Undefined);
}

XResultCode XDialerImpl::unregisterConnection(const ConnectionId& handle) {
    std::unique_lock<std::mutex> al(lock_);
    auto it = connection_map_.find(handle);

    if (it != connection_map_.end()) { 
        ConnectionInfo& cinfo = it->second;
        
        if (cinfo.timer_worker) {
            cinfo.running = false;
            cinfo.timer_worker->join();
            cinfo.timer_worker = nullptr;
        }
        connection_map_.erase(it);
        return { };
    }

    return XResultCode::FromError(XErrC::NotFound);
}

} //namespace xbus::com::internal